from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout,
                               QLabel, QLineEdit, QPushButton, QMessageBox)
from PySide6.QtCore import Qt
from PySide6.QtGui import QFont, QIcon, QPixmap
from controllers.auth import AuthController
from pathlib import Path
from utils.db import db


class LoginWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.auth_controller = AuthController()
        # 获取项目根目录路径
        self.project_root = Path(__file__).parent.parent.parent
        # 设置图片路径
        self.logo_path = self.project_root.parent / "assets" / "logo.webp"
        self.setWindowIcon(QIcon(str(self.project_root.parent / "assets" / "dialog_icon.svg")))
        self.setup_ui()
        self.apply_styles()

    def setup_ui(self):
        try:
            # 设置窗口基本属性
            self.setWindowTitle("理发店管理系统 - 登录")
            self.setFixedSize(800, 500)

            # 创建主布局
            main_layout = QHBoxLayout()

            # 左侧图片区域
            left_widget = QWidget()
            left_widget.setObjectName("leftWidget")
            left_layout = QVBoxLayout()

            # 修改logo加载部分
            logo_label = QLabel()
            if self.logo_path.exists():
                pixmap = QPixmap(str(self.logo_path))
                if not pixmap.isNull():
                    logo_label.setPixmap(pixmap.scaled(300, 500, Qt.KeepAspectRatio, Qt.SmoothTransformation))
                else:
                    raise FileNotFoundError("图片文件已损坏")
            else:
                # 使用矢量图标作为备用
                logo_label.setPixmap(QIcon.fromTheme("system-users").pixmap(300, 500))

            logo_label.setAlignment(Qt.AlignCenter)
            left_layout.addWidget(logo_label)

            left_widget.setLayout(left_layout)

            # 右侧登录区域
            right_widget = QWidget()
            right_widget.setObjectName("rightWidget")
            right_layout = QVBoxLayout()
            right_layout.setSpacing(20)

            # 标题
            title_label = QLabel("理发店管理系统")
            title_label.setObjectName("titleLabel")
            title_label.setAlignment(Qt.AlignCenter)
            title_label.setStyleSheet("""
                QLabel {
                    background-color: #ffffff;
                    font-family: 'Microsoft YaHei';
                }
            """)

            # 用户名输入框
            self.username_input = QLineEdit()
            self.username_input.setPlaceholderText("请输入用户名")
            self.username_input.setObjectName("inputField")

            # 密码输入框
            self.password_input = QLineEdit()
            self.password_input.setPlaceholderText("请输入密码")
            self.password_input.setEchoMode(QLineEdit.Password)
            self.password_input.setObjectName("inputField")

            # 登录按钮
            self.login_button = QPushButton("登录")
            self.login_button.setObjectName("loginButton")
            self.login_button.clicked.connect(self.handle_login)

            # 添加组件到右侧布局
            right_layout.addStretch()
            right_layout.addWidget(title_label)
            right_layout.addWidget(self.username_input)
            right_layout.addWidget(self.password_input)
            right_layout.addWidget(self.login_button)
            right_layout.addStretch()

            right_widget.setLayout(right_layout)

            # 添加左右两侧到主布局
            main_layout.addWidget(left_widget)
            main_layout.addWidget(right_widget)

            self.setLayout(main_layout)
        except Exception as e:
            QMessageBox.critical(self, "资源错误",
                                 f"无法加载图标资源：{str(e)}\n"
                                 "请检查以下路径是否存在：\n"
                                 f"{self.logo_path}")

    def apply_styles(self):
        self.setStyleSheet("""
            QWidget {
                background-color: #f5f6fa;
                font-family: 'Microsoft YaHei';
            }
            #leftWidget {
                background-color: #2f3542;
                border-radius: 10px;
                margin: 10px;
            }
            #rightWidget {
                background-color: white;
                border-radius: 10px;
                margin: 10px;
                padding: 20px;
            }
            #titleLabel {
                font-size: 24px;
                font-weight: bold;
                color: #2f3542;
                margin: 20px;
            }
            #inputField {
                padding: 10px;
                border: 2px solid #dcdde1;
                border-radius: 5px;
                font-size: 14px;
                min-height: 20px;
                margin: 5px 20px;
            }
            #inputField:focus {
                border-color: #5352ed;
            }
            #loginButton {
                background-color: #5352ed;
                color: white;
                border: none;
                border-radius: 5px;
                padding: 10px;
                font-size: 16px;
                min-width: 200px;
                margin: 20px;
            }
            #loginButton:hover {
                background-color: #3742fa;
            }
        """)

    def handle_login(self):
        username = self.username_input.text().strip()
        password = self.password_input.text().strip()

        if not username or not password:
            QMessageBox.warning(self, "警告", "用户名和密码不能为空！")
            return

        success, message = self.auth_controller.login(username, password)

        if success:
            from views.main import MainWindow
            self.main_window = MainWindow(self.auth_controller.get_current_user())
            self.main_window.show()
            self.close()
        else:
            QMessageBox.warning(self, "错误", message)
